package com.demo.cms.action.user;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.demo.Constants;
import com.demo.cms.model.Article;
import com.demo.cms.model.Category;
import com.demo.core.dao.base.support.ResultSearchResult;
import com.demo.core.model.Template;
import com.demo.webapp.action.TemplateProvider;

/**
 * 栏目Action
 * 前端页面展示的Acttion
 * <br>根据栏目地址或栏目ID查找栏目,并找到其模板加以渲染
 * @author ryuu.kk
 *
 */
public class CategoryAction extends ClientBaseAction implements TemplateProvider {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = 5457908809351588642L;

	/**
	 * 模板模型
	 */
	private Template template;
	
	/**
	 * 栏目模型
	 */
	private Category category;
	
	/**
	 * 文章列表
	 */
	private List<Article> articleList;
	
	@Override
	public String execute() {
		
		// 请求的前期处理
		super.prepare();
		
		if (StringUtils.isNotEmpty(getCategoryPath())) {
			this.category = getCategoryService().find(getCategoryPath());
		}
		if (category == null && getCategoryId() != null) {
			this.category = getCategoryService().find(getCategoryId());
		} 
		if (category == null ){
			// 找不到栏目模型,提示错误
			// 找到错误提示模板,并生成错误提示.
			// 错误提示模板将与其他模板一样,可编辑.
			// do some thing;
			return INPUT;
		}
		
		// 得到栏目,应判断一下是否有权访问
		category.isPermission();//？
		
		// 得到栏目下的文章列表(需要分页+排序)
		ResultSearchResult<Article> articleResult = getArticleService().search(category.getId(), "", getArgumentSupport());
		this.articleList = new ArrayList<Article>(articleResult.getResults());
		setResultSupport(articleResult);
		
		// 取得渲染模板
		template = super.findTemplate(category.getTemplateId());
		return SUCCESS;
	}
	
	@Override
	public Template getTemplateModel() {
		return this.template;
	}
	
	// ~~ setter here ============================
	public String getActionType() {
		return Constants.ACTION_TYPE_CATEGORY;
	}

	public Category getCategory() {
		return category;
	}

	public List<Article> getArticleList() {
		return articleList;
	}
}
